package com.my.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.reggie.common.R;
import com.my.reggie.dto.DishDto;
import com.my.reggie.pojo.Category;
import com.my.reggie.pojo.Dish;
import com.my.reggie.pojo.DishFlavor;
import com.my.reggie.service.CategoryService;
import com.my.reggie.service.DishFlavorService;
import com.my.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name){
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dtoPage = new Page<>();
        //构造条件过滤器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(name != null,Dish::getName,name);
        //添加排序条件，按照员工创建时间排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行查询
        dishService.page(pageInfo,lqw);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<DishDto> lists = new ArrayList<>();
        //遍历每一条记录，以便给每个DishDto对象赋categoryName
        for (Dish record : pageInfo.getRecords()) {
            DishDto dishDto = new DishDto();
            //拷贝属性，此时还差categoryName属性没有值
            BeanUtils.copyProperties(record,dishDto);
            //获取分类id
            Long categoryId = record.getCategoryId();
            //通过id获取每条category数据
            Category category = categoryService.getById(categoryId);
            //获取每条category数据的名称
            String T_name = category.getName();
            //给每个DishDto对象的categoryName属性赋值
            dishDto.setCategoryName(T_name);
            //将该条记录添加到list中
            lists.add(dishDto);
        }
        //设置dtoPage的records值
        dtoPage.setRecords(lists);
        return R.success(dtoPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @Transactional    //多表操作，添加事务管理
    public R<String> save(@RequestBody DishDto dishDto){
        // log.info(dishDto.toString());
        //精确清理菜品缓存(只清理某一类)
        //构建key
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        //删除缓存
        redisTemplate.delete(key);
        dishService.save(dishDto);
        for (DishFlavor flavor : dishDto.getFlavors()) {
            flavor.setDishId(dishDto.getId());
            dishFlavorService.save(flavor);
        }
        return R.success("添加成功！");
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable("id") Long id){
        DishDto dishDto = new DishDto();
        //查询dish
        Dish dish =  dishService.getById(id);
        //将dish的属性设置拷贝给子类dishDto
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        //获取dishFlavorsList
        List<DishFlavor> list = dishFlavorService.list(lqw);
        // 设置属性
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    @Transactional
    public R<String> update(@RequestBody DishDto dishDto){
        //构建key
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        //删除缓存
        redisTemplate.delete(key);
        dishService.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
        //迭代修改
        for (DishFlavor flavor : dishDto.getFlavors()) {
            flavor.setDishId(dishDto.getId());
            dishFlavorService.save(flavor);
        }
        return R.success("修改成功！");
    }

    /**
     * 删除菜品(含批量删除)
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long[] ids){
        for (Long id : ids) {
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId, id);
            LambdaQueryWrapper<Dish> DLqw = new LambdaQueryWrapper<>();
            DLqw.eq(Dish::getId,id);
            Dish dish = dishService.getOne(DLqw);
            //构建key
            String key = "dish_" + dish.getCategoryId() + "_1";
            //删除缓存
            redisTemplate.delete(key);
            dishFlavorService.remove(lqw);
            dishService.removeById(id);
        }
        return R.success("删除成功！");
    }

    /**
     * 更改售卖状态(含批量操作)
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable String status, Long[] ids){
        for (Long id : ids) {
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Dish::getId,id);
            Dish dish_temp = dishService.getOne(lqw);
            String key = "dish_" + dish_temp.getCategoryId() + "_1";
            redisTemplate.delete(key);
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(Integer.valueOf(status));
            dishService.updateById(dish);
        }
        return R.success("更新成功！");
    }

    /**
     * 获取菜品列表(套餐管理)
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getList(Dish dish){
        List<DishDto> dishDtoList = null;
        //拼接key值
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //获取Redis缓存
        dishDtoList = (List<DishDto>)redisTemplate.opsForValue().get(key);
        if(dishDtoList != null) {
            //获取缓存成功
            return R.success(dishDtoList);
        }
        //获取缓存失败，需要查询数据库,并将获取结果缓存到Redis
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(dish.getName() != null,Dish::getName,dish.getName());
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort);
        //获取dish集合
        List<Dish> list = dishService.list(lqw);
        dishDtoList = new ArrayList<>();
        for(Dish dish1 : list){
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1,dishDto);
            LambdaQueryWrapper<DishFlavor> dfLqw = new LambdaQueryWrapper<>();
            dfLqw.eq(DishFlavor::getDishId,dish1.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(dfLqw);
            dishDto.setFlavors(flavorList);
            dishDtoList.add(dishDto);
        }
        //将数据缓存到Redis，60分钟后被清理
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
